<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Builder as Eloquent_Builder;
use Illuminate\Database\Query\Builder as Query_Builder;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //增加分页助手方法
        $autoPaginate = function (bool $get_total = true, int $defaultPage = null, int $defaultPerPage = null) {
            !$defaultPage && $defaultPage = (int)request()->input('page', 1);
            !$defaultPerPage && $defaultPerPage = (int)request()->input('per_page', 15);

            $res = [];
            $res['page'] = $defaultPage;
            $res['per_page'] = $defaultPerPage;
            if ($get_total) {
                $res['total'] = $this->count();
            }

            $res['list'] = [];
            if (!isset($res['total']) || !empty($res['total'])) {
                $res['list'] = $this->forPage($defaultPage, $defaultPerPage)->get();
            }

            return $res;
        };
        Query_Builder::macro('autoPaginate', $autoPaginate);
        Eloquent_Builder::macro('autoPaginate', $autoPaginate);
    }
}
